package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RatingBar;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Comment;
import com.woyao.core.model.GetCommentResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;


public class CommentActivity extends AppCompatActivity {

    private EditText descTxt;
    private EditText chargeTxt;
    private RadioGroup needPermit;

    private RatingBar rateBar;

    private  Button nextBtn;

    ProgressDialog progressDialog;
    private Comment comment = new Comment();



    private boolean loading = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_edit);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        rateBar = (RatingBar)  findViewById(R.id.id_comment_rating);


        rateBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                if (loading) return;
                if (comment.getId() > 0 ) {
                    Common.setCommentAttrFeedback(CommentActivity.this,comment.getId(),"rate", Float.toString(ratingBar.getRating())  );
                }
            }
        });

        descTxt  = (EditText) findViewById(R.id.id_comment_description);


        descTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (loading ) {
                    return;
                }
                try{
                    comment.setDescription( descTxt.getText().toString());
                    if (comment.getId() > 0 ) {
                        Common.setCommentAttrFeedback(CommentActivity.this, comment.getId(), "description", comment.getDescription() + "");
                    }
                }catch(Exception e) {
                    descTxt.requestFocus();
                    descTxt.selectAll();
                }

            }
        });

        chargeTxt = (EditText) findViewById(R.id.id_comment_charge);

        chargeTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (loading ) {
                    return;
                }
                try{
                    comment.setCharge(Float.parseFloat(chargeTxt.getText().toString() ));
                    if (comment.getId() > 0 ) {
                        Common.setCommentAttrFeedback(CommentActivity.this, comment.getId(), "charge", comment.getCharge() + "");
                    }
                }catch(Exception e) {

                    chargeTxt.requestFocus();
                    chargeTxt.selectAll();
                }

            }
        });



        Button delBtn= (Button) findViewById(R.id.comment_delete);

        delBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Dialog alertDialog = new AlertDialog.Builder(CommentActivity.this).
                        setTitle("信息").
                        setMessage("删除吗？").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                               deleteIt();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();

            }
        });

        nextBtn = (Button) findViewById(R.id.comment_next);

        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( descTxt.getText().toString().trim().equals("")){
                    Common.alert(CommentActivity.this, "请输入评论内容");
                    descTxt.requestFocus();
                    return;
                }

                if (comment.getId() == 0 ){
                    addComment();
                }else {
                    Intent intent = new Intent();
                    intent.putExtra("changed", true);
                    setResult(666, intent);
                    finish();
                }
            }
        });

        Intent intent = getIntent();
        Boolean is_new = intent.getBooleanExtra("is_new", false);

        if (is_new ) {
            Integer partner_id = intent.getIntExtra("partner_id", 0);
            comment.setPartner_id( partner_id);
            this.setTitle( "添加评论");
            delBtn.setVisibility(View.GONE);

        }else{
            Integer id = intent.getIntExtra("id", 0);
            comment.setId( id );
            this.setTitle( "评论内容");
            loadData();
        }

    }


    private  void deleteIt(){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setCommentAttr(WoyaoooApplication.userId,comment.getId(),"available","0");
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {
                    if (response.isSuccess()){
                        Intent intent = new Intent();
                        intent.putExtra("changed", true);
                        setResult(666, intent);
                        finish();
                    }else{
                        Common.alert( CommentActivity.this,response.getMessage());
                    }
                } else {
                    Common.alert( CommentActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }

    private void renderIt() {
        loading = true;

        this.setTitle( comment.getTitle());
        descTxt.setText(comment.getDescription());
        chargeTxt.setText(comment.getCharge() +"");

        rateBar.setRating( comment.getRate());

        loading = false;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", true );
        setResult(0, intent);
        finish();
        return true;
    }

    private void addComment(){

        final Integer rateStar = (int)(rateBar.getRating() + 0.1);
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在处理······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> needTask = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.addComment(userId,comment.getPartner_id(),rateStar,comment.getDescription(),comment.getCharge(),comment.getNeed_permit());
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null ) {
                    if  (response.isSuccess()){
                        Intent intent = new Intent();
                        intent.putExtra("changed", true );
                        setResult(666, intent);
                        finish();
                    }else{
                        Common.alert(CommentActivity.this,response.getMessage());
                    }
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }



    private void loadData() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        AsyncTask<Void, Void, GetCommentResponse> needTask = new AsyncTask<Void, Void, GetCommentResponse>() {
            @Override
            protected GetCommentResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetCommentResponse> responseCall = svc.getComment(userId, comment.getId());
                try {
                    GetCommentResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final GetCommentResponse response) {
                if (response != null && response.getContent() != null) {
                    comment = response.getContent();


                    renderIt( );

                    if (!response.getMessage().equals("")) {
                        Common.alert(CommentActivity.this, response.getMessage());
                    }
                }
                progressDialog.dismiss();
            }
        };
        needTask.execute((Void) null);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", true );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}